// app.js
import api from './utils/index'
// vant-weapp 开发文档
// https://youzan.github.io/vant-weapp/#/quickstart

App({
    globalData: {
        api,
        // 小数位保留位数初始化
        setData: {
          num: 2,
          price: 2,
          amount: 2,
        }
    },
    isReal: false, // 是否真实地址，通过中台换取
    project: '', // 默认项目文件夹（一个域名对应一个项目则留空不填）,只在微信环境下生效
    domainName: 'https://demo.yumukeji.com/project/txhg/',
    domain: '',
    root: '',
    // 中台地址，注意：都不填则不走服务商逻辑（三合一后就废弃了）
    controlDomain: '', // https://admin.saas.yumukeji.com/
    controlRoot: '', // https://admin.saas.yumukeji.com/interface/v1/
    
    onLaunch() {
      const that = this, token = wx.getStorageSync('token')
      const isWxwork = api.isWxwork()
      this.domain = wx.getStorageSync('realDomain') ? 
                  wx.getStorageSync('realDomain') : 
                  this.domainName + (this.project && !isWxwork ? this.project + '/' : '');
      this.root = wx.getStorageSync('realUrl') ? 
                  wx.getStorageSync('realUrl') : 
                  this.domainName + (this.project && !isWxwork ? this.project + '/' : '') + 'interface/v1/';

        if (token === '-1') {
            wx.clearStorageSync('token')
        }
        App({
            onLaunch: function () {
                // 检测更新
                const updateManager = wx.getUpdateManager()
                updateManager.onCheckForUpdate(function (res) {
                    // 请求完新版本信息的回调
                    // console.log(res.hasUpdate)
                })
                updateManager.onUpdateReady(function () {
                    wx.showModal({
                        title: '更新提示',
                        content: '新版本已经准备好，是否重启应用？',
                        success(res) {
                            if (res.confirm) {
                                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                                wx.clearStorageSync()
                                updateManager.applyUpdate()
                            }
                        }
                    })
                })
                // that.triggerLogin() 
            }
        })
    },
    onShow: function() {
      setTimeout(() => {
        const pages = getCurrentPages()
        const route = '/' + pages[pages.length - 1].route
        const options = pages[pages.length - 1].options
        if (JSON.stringify(options) !== '{}') {
          //参数多时通过&拼接url的参数
          var urlWithArgs = route + '?'
          for (var key in options) {
            var value = options[key]
            urlWithArgs += key + '=' + value + '&'
          }
          urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
          wx.setStorageSync('fromUrl', encodeURIComponent(urlWithArgs))
        }else{
          wx.setStorageSync('fromUrl', encodeURIComponent(route))
        }
      }, 100); // 延迟 0ms 等待页面栈初始化
    },
    triggerLogin: function() {
      let that = this
      let isWxwork = api.isWxwork()
      //  判断是否为企业微信
      if (!isWxwork) {
        // 微信登录
        that.wechatLogin()
        // api.showToast('暂不支持微信登录使用', 'none', 99999999999999)
      } else {
          let realUrl = wx.getStorageSync('realUrl')
          // 没有接口地址，并且有中台地址，则走服务商逻辑
          if (!realUrl && that.controlRoot) {
              //先生成uid，再根据流程配置
              that.getUid();
          } else {
              that.startRequest()
          }
      }
    },
    resetGlobalData: function(domain, root) {
      this.domain = domain;  // 重置 domain
      this.root = root;  // 重置 root
    },
    // 本地地址请求
    startRequest() {
        let that = this;
        let token = wx.getStorageSync('token');
        if (token === -1) {
            wx.setStorageSync('token', '')
        }
        if (!api.isWxwork()) {
            console.log('微信环境')
            //微信环境
            that.wechatLogin()
        } else {
            //企业微信环境
            wx.qy.checkSession({
                success: function () {
                    //session_key 未过期，并且在本生命周期一直有效
                    console.log('没到期，心跳检测')
                    api.heartBeat()
                },
                fail: function () {
                    // session_key 已经失效，需要重新执行登录流程
                    console.log('到期，重新登录')
                    api.login()
                }
            })
        }
    },

    // SaaS--获取UID 并换取中台服务器接口地址
    getUid() {
        let that = this;
        wx.qy.login({
            //第三方应用的suiteid，若第三方小程序绑定多个第三方应用时，建议填上该字段。自建应用不填，且必须去掉
            suiteId: 'wwad3a2330bdc6a021',
            success: function (res) {
                if (res.code) {
                    wx.request({
                        url: that.controlRoot + '?cla=loginApp&fun=getUid',
                        method: 'POST',
                        header: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Source": 'erp3',
                            "Auth": wx.getStorageSync('token')
                        },
                        data: {code: res.code},
                        success: async resp => {
                            const res = resp.data
                            // 通过uid 和 corpid 请求中台获取服务端地址
                            if (res.code === 1 && !res.data.isLocal) {
                                if (res.data.corpid) wx.setStorageSync('corpid', res.data.corpid)
                                if (res.data.session_key) wx.setStorageSync('session_key', res.data.session_key)
                                if (res.data.uid) {
                                    wx.setStorageSync('userid', res.data.uid)
                                    wx.setStorageSync('uid', res.data.uid)
                                }
                                var uid = res.data.uid
                                /*if(res.data.corpid == 'wwade682b3c2b313bd'){
                                  uid = res.data.open_userid
                                }*/
                                // 通过uid 换取远程服务器地址
                                that.getServerUrl(uid, res.data.corpid)
                            } else {
                                // 使用本地接口登录
                                that.startRequest()
                            }
                        }, fail(err) {
                            console.log(err)
                            reject(err)
                        }
                    })
                }
            }
        });
    },
    // 获取服务端真实地址
    getServerUrl(uid, corpid) {
        let that = this
        wx.removeStorageSync('realUrl')
        wx.request({
            url: that.controlRoot + 'wechatInitClass.php?fun=getServerUrl', //中控台地址
            header: {
                'content-type': "application/x-www-form-urlencoded",
                "Source": 'erp3',
            },
            data: {uid: uid, corpid: corpid},
            method: 'POST',
            success(res) {
                if (res.data.code !== 1) {
                    setTimeout(function () {
                        wx.redirectTo({
                            url: '/pages/init/init',
                        })
                    }, 1000)
                } else {
                    const root = res.data.data.url.replace('?', '')
                    wx.setStorageSync('realUrl', root)
                    that.root = root
                    that.startRequest();
                }
            }
        })
    },
    clearStorage() {
      let that = this;
      wx.showModal({
        title: '提示',
        content: '你将清空小程序本地所有缓存',
        success: function (res) {
            //判断用户是否点击了确定
            if (res.confirm) {
              if (that.controlRoot && api.isWxwork()) {
                that.delUser()
                wx.clearStorageSync()
                // 重新登录
                that.getUid()
              } else {
                let code = wx.getStorageSync('code')
                let userName = wx.getStorageSync('userName')
                let password = wx.getStorageSync('password')
                let openid = wx.getStorageSync('openid')
                wx.clearStorageSync()
                
                wx.setStorageSync('code', code)
                wx.setStorageSync('userName', userName)
                wx.setStorageSync('password', password)
                wx.setStorageSync('openid', openid)
                wx.redirectTo({
                  url: '/pages/login/index?logout=1'
                })
              }
            }
        }
    })
  },
  delUser() {
    let that = this;
    const params = {
        'uid': wx.getStorageSync('userid'),
        'corpid': wx.getStorageSync('corpid'),
    }
    wx.request({
        url: that.controlRoot + 'wechatInitClass.php?fun=delUser', //中控台地址
        header: {
            'content-type': "application/x-www-form-urlencoded",
            "Source": 'erp3',
        },
        data: params,
        method: 'POST',
        success(res) {
            return res.data.code
        }
    })
  },

  /**微信小程序登录 */
  wechatLogin() {
    let that = this;
    wx.removeStorageSync('token')
    wx.login({
        success: async function (res) {
            if (res.code) {
                //发起网络请求
                const resp = await api.curlPost('?cla=loginApp&fun=weChatLogin', {
                    code: res.code,
                    platform: 'wechat',
                }, that.root)
                if (resp.code === 1) {
                  wx.setStorageSync('openid', resp.data.openid)
                  if(resp.data.token){
                    wx.setStorageSync('token', resp.data.token)
                    wx.reLaunch({
                        url: '/pages/index/index'
                    })
                  }else{
                    wx.redirectTo({
                      url: '/pages/login/index'
                    })
                  }
                }
            } else {
                api.showToast('登录失败！' + res.errMsg)
            }
        }
    });
  },
})
